package com.example.wto.myapplication;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Spi {
	String cookie = "";
	private final static String WEEK[]={"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);

		Spi spi = new Spi();

		List<String> tlist = spi.getIndex();

		// ��ȡ��֤��
		spi.getImage();

		for (String string : tlist) {
			System.out.println(string);
		}
		System.out.println("����ѧ�ں�");
		String tid = sca.next();

		// ����ѧ�ڻ�ȡ��ʦ
		List<String> teaList = spi.getTeachers(tid);
		for (String string : teaList) {
			System.out.println(string);
		}

		System.out.println("�����ʦ��");
		String teaid = sca.next();

		System.out.println("������֤��");

		String code = sca.next();
		Map<Integer, List<Course>> cmap = spi.sendPost(tid, teaid, code);
		int i=0;
		int j=0;
		Teacher teacher =new Teacher("1","tom");
		teacher.setS_id("20161");
		teacher.getWeekList().clear();
		if (cmap != null)
		{
			for (Entry<Integer, List<Course>> l : cmap.entrySet()) {
				System.out.println(WEEK[j++]);
				if(j>=7)
				{
					break;
				}
				i=0;

				DayOfWeek weekDay=new DayOfWeek(WEEK[j]);
				weekDay.setCourseList(l.getValue());
				teacher.getWeekList().add(weekDay);
				for (Course o : l.getValue()) {
					System.out.println("��"+(++i)+"�ڿ�");

					System.out.println(o.toString());
				}

			}
			System.out.println(teacher.toJsonObject());
		}
		else
			System.out.println("����");
	}

	private List<String> getIndex() {
		try {
			URL url = new URL("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			Map<String, List<String>> map = conn.getHeaderFields();
			cookie = map.get("Set-Cookie").get(0);
			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			String index = builder.toString();
			reader.close();
			conn.disconnect();

			Document doc = Jsoup.parse(index);
			Elements elements = doc.select("select[name=\"Sel_XNXQ\"] option");
			List<String> termList = new ArrayList<>();
			for (Element element : elements) {
				String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
				termList.add(t);
			}

			return termList;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// �������� ��ѧ�� ��ʦ ��֤�뷢�͹�ȥ
	private Map<Integer, List<Course>> sendPost(String termId, String tid, String code) {
		try {
			URL url = new URL("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB_rpt.aspx");
			String param = "Sel_XNXQ=" + termId + "&Sel_JS=" + tid + "&type=" + 1 + "&txt_yzm=" + code;
			// Connection con =
			// Jsoup.connect("http://jw.zzti.edu.cn/ZNPK/TeacherKBFB_rpt.aspx");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setRequestProperty("Cookie", cookie);
			conn.setRequestProperty("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36");
			conn.setRequestProperty("Upgrade-Insecure-Requests", "1");
			conn.setRequestProperty("Referer", "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
			conn.setRequestProperty("Origin", "http://jw.zzti.edu.cn");
			conn.setRequestProperty("Cache-Control", "max-age=0");

			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(param);
			dos.flush();
			dos.close();

			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			String info = builder.toString();

			Document doc = Jsoup.parse(info);
			Elements elements = doc.select("td");
			elements.get(0);

			Map<Integer, List<Course>> cmap = new LinkedHashMap<>();

			List<Course> cl1 = new ArrayList<Course>();
			List<Course> cl2 = new ArrayList<Course>();
			List<Course> cl3 = new ArrayList<Course>();
			List<Course> cl4 = new ArrayList<Course>();
			List<Course> cl5 = new ArrayList<Course>();
			List<Course> cl6 = new ArrayList<Course>();
			List<Course> cl7 = new ArrayList<Course>();

			cmap.put(1, cl1);
			cmap.put(2, cl2);
			cmap.put(3, cl3);
			cmap.put(4, cl4);
			cmap.put(5, cl5);
			cmap.put(6, cl6);
			cmap.put(7, cl7);

			for (Element week : elements) {
				if (week.html().equals("����һ")) {
					Element wtr = week.parent();
					Elements trs = wtr.siblingElements();
					for (int j = 0; j < trs.size(); j++) {
						Element tr = trs.get(j);
						Elements trds = tr.children();
						int ncounter = 0;
						for (int i = 0; i < trds.size(); i++) {
							Element td = trds.get(i);

							if (td.attr("valign").equals("top")) {
								if (td.text() != null)
									cmap.get(i - ncounter + 1).add(new Course(td.text() + ""));
								else
									cmap.get(i - ncounter + 1).add(new Course(""));
							} else
								ncounter++;
						}
					}
					return cmap;
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	private void getImage() {
		//
		try {
			URL url = new URL("http://jw.zzti.edu.cn/sys/ValidateCode.aspx");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Cookie", cookie);
			conn.setRequestProperty("Referer", "http://jw.zzti.edu.cn/ZNPK/TeacherKBFB.aspx");
			InputStream in = conn.getInputStream();
			File file = new File("image.jpg");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fo = new FileOutputStream(file);
			byte[] buf = new byte[1024];
			int length = 0;
			while ((length = in.read(buf, 0, buf.length)) != -1) {
				fo.write(buf, 0, length);
			}
			in.close();
			fo.close();
			conn.disconnect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	// ��ȡȫ����ʦ
	private List<String> getTeachers(String term) {
		try {
			URL url = new URL("http://jw.zzti.edu.cn/ZNPK/Private/List_JS.aspx?xnxq=" + term + "&t=276");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("Cookie", cookie);
			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			String info = builder.toString();

			reader.close();
			conn.disconnect();

			Document doc = Jsoup.parse(info);
			doc = Jsoup.parse(doc.select("script").html().substring(24));
			Elements eles = doc.select("select[name=\"Sel_JS\"] option");
			List<String> slist = new ArrayList<>();
			for (Element element : eles) {
				String t = " {\"id\":" + element.val() + ",\"name\":" + element.html() + "}";
				slist.add(t);
				// System.out.println(t);
			}

			return slist;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String string2Unicode(String string) {

		StringBuffer unicode = new StringBuffer();

		for (int i = 0; i < string.length(); i++) {

			// ȡ��ÿһ���ַ�
			char c = string.charAt(i);

			// ת��Ϊunicode
			unicode.append("\\u" + Integer.toHexString(c));
		}

		return unicode.toString();
	}

}
